package vip.xiaonuo.biz;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import vip.xiaonuo.biz.core.utils.RedisUtil;
import vip.xiaonuo.biz.modular.esmapping.BizGoodsBoxESMapper;
import vip.xiaonuo.biz.modular.lancerGoods.service.BizGoodsService;
import vip.xiaonuo.biz.modular.lancerGoodskill.entity.BizGoodsKill;
import vip.xiaonuo.biz.modular.lancerGoodskill.service.BizGoodsKillService;
import vip.xiaonuo.common.consts.CacheConstant;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RunServe implements CommandLineRunner {
    @Resource
    RedissonClient redissonClient;
    @Autowired
    BizGoodsService goodsService;

    @Override
    // 加载库存至redis
    public void run(String... args){
        // 加载库存至redis
        loadRedisSkillInfo();

        // 自动关单的线程
        new Thread(()->{
            // 创建/获取 阻塞队列
            RBlockingQueue<String> blockingFairQueue = redissonClient.getBlockingQueue("orderQueue");
            // 创建/获取 延时队列，并设置当延时队列中的数据到期后将数据放入到阻塞队列中，这里的阻塞队列有点类似RabbitMq中的死信队列，对应的流程也很类型
            RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
            // 设置一个空值，1s后可以被take到，主要是测试下。
            delayedQueue.offer("test", 1, TimeUnit.SECONDS);
            while (true){
                String orderId = null;
                try {
                    // 尝试从阻塞队列中获取一个订单
                    orderId = blockingFairQueue.take();
                    if (orderId.equals("test")){
                        log.info("Redis的订单自动关停的，阻塞队列、延时队列正常");
                        continue;
                    }
                    boolean res = goodsService.isPaid(orderId);
                    if (!res){
                        log.info("订单未支付并且超时了：OrderId"+orderId);
                        // 支付关闭，订单取消
                        goodsService.closeOrder(orderId);
                    }
                } catch (Exception e) {
                    continue;
                }
            }
        }).start();
    }

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    BizGoodsKillService goodsKillService;
    // 加载库存至redis
    public void loadRedisSkillInfo(){
        List<BizGoodsKill> allSkillInfo = goodsKillService.getAllSkillInfo();
        for (BizGoodsKill kill : allSkillInfo) {
            redisUtil.hset(CacheConstant.SKILL_GOODS_CACHE_KEY,kill.getId(), kill.getOriginCurrStock());
        }
        log.info("初始化秒杀商品至缓存成功");
    }
}
